package by.yakusekmaxim.bookgid.webapp.page.admin.genre;

import java.util.List;

import javax.inject.Inject;

import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.ResourceModel;

import by.yakusekmaxim.bookgid.dataaccess.util.Filter;
import by.yakusekmaxim.bookgid.datamodel.Book;
import by.yakusekmaxim.bookgid.datamodel.Book_;
import by.yakusekmaxim.bookgid.datamodel.Genre;
import by.yakusekmaxim.bookgid.services.BookService;
import by.yakusekmaxim.bookgid.services.GenreService;
import by.yakusekmaxim.bookgid.webapp.page.AdminLayout;
import by.yakusekmaxim.bookgid.webapp.page.admin.book.BookPage;

public class GenrePage extends AdminLayout {

	@Inject
	private GenreService genreService;

	@Inject
	private BookService bookService;

	protected void onInitialize() {
		super.onInitialize();

		add(new Link<Object>("linkEditGenrePage") {
			@Override
			public void onClick() {
				setResponsePage(new EditGenrePage(new Genre()));
			}
		});

		add(new Label("count", genreService.getCount()));

		final List<Genre> allGenre = genreService.getAll();

		add(new ListView<Genre>("details-panel", allGenre) {
			@Override
			protected void populateItem(ListItem<Genre> item) {
				final Genre genre = item.getModelObject();
				item.add(new Label("id", genre.getId()));
				item.add(new Label("name", genre.getName()));

				Link<Object> linkAuthor = new Link<Object>("linkBook") {
					@Override
					public void onClick() {
						Filter<Book> filter = new Filter<Book>();
						filter.setEnabled(true);
						filter.setAttribute(Book_.genre);
						filter.setValue(genre);
						setResponsePage(new BookPage(filter, new ResourceModel(
								"p.admin.genre.bookLink").getObject()
								+ genre.getName()));

					}
				};

				linkAuthor
						.setEnabled(bookService.getCount(Book_.genre, genre) != 0);
				linkAuthor.add(new Label("bookCount", bookService.getCount(
						Book_.genre, genre)));
				item.add(linkAuthor);

				item.add(new Link<Object>("delete") {
					@Override
					public void onClick() {
						genreService.delete(genre);
						GenrePage genrePage = new GenrePage();
						genrePage.info("Жанр: " + genre.getName() + " удалён!");
						setResponsePage(genrePage);
					}
				});
				item.add(new Link<Object>("edit") {
					@Override
					public void onClick() {
						setResponsePage(new EditGenrePage(genre));
					}
				});
			}
		});
	}

	@Override
	protected IModel<String> getPageTitle() {
		return new ResourceModel("adminmenu.genres");
	}

	@Override
	protected WebMarkupContainer getTarget() {
		return targetGenre;
	}

}
